package beer.zivelin.awesome.walawala.mobile;

import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowMetrics;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.common.base.Stopwatch;
import com.google.common.base.Strings;

import java.util.concurrent.TimeUnit;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import beer.zivelin.awesome.walawala.mobile.service.ApplicationLocator;
import beer.zivelin.awesome.walawala.mobile.service.T9;
import beer.zivelin.awesome.walawala.mobile.ui.ApplicationViewHelper;
import beer.zivelin.awesome.walawala.mobile.ui.SearchEditorWatcher;

public class MainActivity extends AppCompatActivity {

    ApplicationLocator applicationLocator;
    SearchEditorWatcher searchEditorWatcher;


    @RequiresApi(api = Build.VERSION_CODES.R)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d(Tester.TAG, "on create");
        super.onCreate(savedInstanceState);

        if (applicationLocator == null) {
            applicationLocator = new ApplicationLocator(this);
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE);


        this.setFinishOnTouchOutside(true);

        this.setContentView(R.layout.content_main);


        final TextView t9SearchEditor = findViewById(R.id.t9_input);
        final ImageButton reloadAppButton = findViewById(R.id.reload_app_button);
        final LinearLayout resultView = findViewById(R.id.result_view);
        final GridLayout buttonView = findViewById(R.id.button_view);
        final Button searchLikeBt = findViewById(R.id.bt_search_like);
        searchEditorWatcher = new SearchEditorWatcher(resultView, applicationLocator, searchLikeBt,this);
        t9SearchEditor.addTextChangedListener(searchEditorWatcher);

        reloadAppButton.setOnClickListener(e -> {
            reloadAppButton.setImageResource(R.mipmap.ic_launcher);
            new Thread(() -> {
                applicationLocator.refreshApplications(locator -> {
                    MainActivity.this.runOnUiThread(() -> {
                        reloadAppButton.setImageResource(R.mipmap.ic_launcher_foreground);
                        ApplicationViewHelper.clearSearchEditor(t9SearchEditor, searchEditorWatcher);
                    });
                });

            }).start();
        });


        ApplicationViewHelper.initialT9Buttons(buttonView, t9SearchEditor, resultView, MainActivity.this);
        try {
            initDialogWindow();
        } catch (Exception e) {
            Log.e(Tester.TAG, "init dialog params error");
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(Tester.TAG, "on destroy");
        if (applicationLocator != null) {
            applicationLocator.close();
        }
    }

    @Override
    protected void onStart() {
        Log.d(Tester.TAG, "on start");
        Stopwatch stopwatch = Stopwatch.createStarted();
        super.onStart();
        TextView t9SearchEditor = findViewById(R.id.t9_input);
        new Thread(() -> {
            applicationLocator.open();
            applicationLocator.loadApplications(locator -> {
                MainActivity.this.runOnUiThread(() -> {
                    Log.w(Tester.TAG, "load used " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
                    if (t9SearchEditor.getText() == null || Strings.isNullOrEmpty(t9SearchEditor.getText().toString())) {
                        ApplicationViewHelper.clearSearchEditor(t9SearchEditor, searchEditorWatcher);
                    }
                });
            });
        }).start();
        ApplicationViewHelper.clearSearchEditor(t9SearchEditor, searchEditorWatcher);
    }

    protected void initDialogWindow() {
        WindowManager manager = getWindowManager();
        int width;
        int height;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Rect bounds = manager.getCurrentWindowMetrics().getBounds();
            height = bounds.height();
            width = bounds.width();
        } else {
            DisplayMetrics metrics = new DisplayMetrics();
            manager.getDefaultDisplay().getMetrics(metrics);
            height = metrics.heightPixels;
            width = metrics.widthPixels;
        }

        WindowManager.LayoutParams windowParams = new WindowManager.LayoutParams();
        windowParams.height = (int) (height * 0.8f);
        windowParams.width = (int) (width * 0.9f);
        windowParams.y = height - (int) (windowParams.height * 1.2f);
        windowParams.alpha = 1.0f;
        windowParams.dimAmount = 0.8f;
        getWindow().setAttributes(windowParams);

    }
}